package com.example.annasbook.powerjob;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.example.annasbook.controller.Index;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBitSet;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import tech.powerjob.worker.core.processor.ProcessResult;
import tech.powerjob.worker.core.processor.TaskContext;
import tech.powerjob.worker.core.processor.sdk.BasicProcessor;
import tech.powerjob.worker.log.OmsLogger;

import java.util.Random;

import static com.example.annasbook.constant.RedisConstant.RANDOM_BOOK_NAME;

// 支持 SpringBean 的形式
@Slf4j
@Component
@RequiredArgsConstructor
public class BasicProcessorDemo implements BasicProcessor {

    private static final  Random r = new Random();

    private final RedissonClient redissonClient;

    private static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    @Override
    public ProcessResult process(TaskContext context) throws Exception {

        // 在线日志功能，可以直接在控制台查看任务日志，非常便捷
        OmsLogger omsLogger = context.getOmsLogger();
        omsLogger.info("BasicProcessorDemo start to process, current JobParams is {}.", context.getJobParams());
        
        // TaskContext为任务的上下文信息，包含了在控制台录入的任务元数据，常用字段为
        // jobParams（任务参数，在控制台录入），instanceParams（任务实例参数，通过 OpenAPI 触发的任务实例才可能存在该参数）
        String params = context.getInstanceParams();
        // 进行实际处理...
//        mysteryService.hasaki();
        String name = findName(params);
        omsLogger.info("find book {}",name);
        // 调用数据爬虫接口，获取书籍信息到redis
        HttpUtil.get(String.format("http://www.leyuee.cn:8081/search?fuzzy=%s", name));
        // 调用save接口存储书籍到数据库
        SpringUtil.getBean(Index.class).saveBook();
        // 返回结果，该结果会被持久化到数据库，在前端页面直接查看，极为方便
        return new ProcessResult(true, "查找书籍：" + name);
    }

    public String findName(String params){
        if(StringUtils.hasText(params)){
            return params;
        }
        r.setSeed(System.currentTimeMillis());
        int length = r.nextInt(3);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(LETTERS.charAt(r.nextInt(LETTERS.length()-1)));
        }
        String name = sb.toString();
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(RANDOM_BOOK_NAME);
        bloomFilter.tryInit(55000000L,0.03);
        if(bloomFilter.contains(name)){
            return findName(null);
        }
        bloomFilter.add(name);
        return name;
    }

//    @Data
//    public static class NameFindInfo{
//        private Integer length;
//
//        private Integer start;
//
//        private String letters;
//    }
}